<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css"-->
<!--          integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">-->
    <link rel="stylesheet" href="../css/pet-store-plus.css">
    <link rel="stylesheet" href="../css/bootstrap.css">
<!--    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">-->
    <script src="/js/chart.js"></script>
<!--    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>-->

    <title>Category管理</title>
</head>
<body>

<div th:replace="seller_commom"></div>
<div class="content" id="content">
    <div style="grid-column: span 3"></div>
    <div class="searchgrp" >
        <form >
            <input type="text" placeholder="可通过商品名搜索..." class="searchinput" id="keyword" name="keyword">
            <button class="searchbtn" onclick="searchCategory()" type="button"  >搜索</button>
        </form>
    </div>

    <button class="Button" style="margin-top: 10px;width: 150px" onclick="window.location.href='/admin/add'"  id="add">
        添加商品
    </button>
    <div class="tab-bg">
        <table class="item_tab"  id="item_tab" style="overflow: auto">
            <caption></caption>
            <thead>
            <tr>
                <th>Id</th>
                <th>名称</th>
                <th>图片</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody id="categoryTabBody">
            </tbody>
        </table>
    </div>
</div>
<script th:inline="javascript">
    const tbody=document.getElementById('categoryTabBody');
    window.addEventListener('load',function (){
        console.log('ccc');
        var url='/admin/showCategory';
        fetch(url,{
            method:'GET',
        }).then(response=>{
            if(!response.ok){
                console.log("请求/admin/showCategory失败，状态码：" + response.status);
            }else {
                return response.json();
            }
        }).then(data=>{
            updateTbody(data.data);
            console.log(data.data);
        }).catch(err=>{
            console.log('error:'+err);
        })
    });

    function updateTbody(newCategorys){
        console.log('update');
        console.log('newCategorys'+newCategorys);
        tbody.innerHTML='';
        newCategorys.forEach(function(category) {


            var newRow = document.createElement('tr');
            newRow.innerHTML=`
                <td name="productid" >${category.catid}</td>
                <td name="productname" >${category.name}</td>

             <td><div class="image-upload-container1">
            <input type="file" id="imageInput1" accept="image/*" name="pic" onchange="previewImage1(event)" style="display: none">
            <img id="imagePreview1" class="image-preview round-image" src="${category.mainimg}" alt="Image Preview" >
            </div></td>
                <td>
                    <button class="edit Button" style="display: inline-block;" onclick="editCategory(this)" id="editCategory">编辑</button>
                    <button class="save Button" style="display: none;" onclick="saveCategory(this)" id="saveCategory">保存</button>
                     <button class="sell-btn Button" style="display: inline-block;" onclick="deleteCategory(this)">删除</button>
                </td>
                    `;


            tbody.appendChild(newRow);
            var preview = newRow.querySelector('.image-preview')
            preview.src = decodeURI(category.mainimg);
            preview.style.display = 'block'; // 在if语句块中显示预览图片
        })

    }

    function editCategory(button){
        var row=button.parentNode.parentNode;
        var saveButton = row.querySelector('#saveCategory');
        var input=row.querySelector('input');
        input.style.display='inline-block';
        button.style.display = "none"; // 隐藏当前行的编辑按钮
        saveButton.style.display='inline-block';
    }


    //还差请求url
    function saveCategory(button) {
        var row = button.parentNode.parentNode;
        var editButton = row.querySelector('#editCategory');
        var catid = row.querySelector('td:nth-child(1)').innerText;
        var imagePreview = row.querySelector('img');
        var fileInput = row.querySelector('input[type=file]')
        var file = fileInput.files[0];
        var formData = new FormData();
        formData.append('categoyrId', catid); // 添加产品ID到 FormData 对象
        // for (var pair of formData.entries()) {
        //     console.log(pair[0] + ', ' + pair[1]);
        // }
        //     fetch('/categoryEditor', {
        //         method: 'POST',
        //         body: formData
        //     })
        //         .then(response => {
        //             if (response.ok) {
        //                 console.log("保存成功");
        //                 console.log("编辑按钮：" + editButton)
        //                 editButton.style.display = 'inline-block';
        //                 button.style.display = 'none';
        //             } else {
        //                 console.log("保存失败");
        //                 alert('商品' + catid + '保存失败');
        //             }
        //             response.json()
        //         }) // 解析响应为 JSON 格式
        //
        //         .catch(error => {
        //             // 处理错误
        //             console.error('Error:', error);
        //         });
        // 检查是否有新的文件被选择，如果没有则使用之前已经上传的文件

        if (file) {
            formData.append('pic', file);
            console.log('pic  file=' + file);
            sendSaveReq(button,formData);
        } else {
            // 如果没有新的文件被选择，则使用之前已经上传的文件
            var imagePreview = row.querySelector('img');

            // 将图片转换为文件对象
            var imageUrl = imagePreview.src;
            var imageName = imageUrl.split('/').pop(); // 获取图片名
            console.log('imageUrl=' + imageUrl);
            console.log('imageName=' + imageName);
            // fetch(imageUrl)
            //     .then(response => response.blob()) // 将图片转换为 Blob 对象
            //     .then(blob => {
            //             var file1 = new File([blob], filename, {type: 'image/jpeg'}); // 创建文件对象
            //         console.log('file='+file1)
            //         var fileURL = URL.createObjectURL(blob);
            //         console.log('fileURL=' + fileURL);
            //             formData.append('pic', file1); // 将文件对象添加到 FormData 中
            //         }
            //     )
            // fetch(relativePath)
            //     .then(response => response.blob()) // 将图像转换为 Blob 对象
            //     .then(blob => {
            //         var file1 = new File([blob], imageName, {type: 'image/jpeg'}); // 创建文件对象
            //         formData.append('pic', file1);
            //         }
            //     ).catch(error=>{
            //     console.error('Error fetching image:', error);
            // })
            imagetoFile(imagePreview,imageName,formData,button);
        }
        console.log('999');


        }
function sendSaveReq(button,formData){
    var row = button.parentNode.parentNode;
    var editButton = row.querySelector('#editCategory');
    fetch('/categoryEditor', {
        method: 'POST',
        body: formData
    })
        .then(response => {
            if (response.ok) {
                console.log("保存成功");
                alert('商品保存成功');
                console.log("编辑按钮：" + editButton)
                editButton.style.display = 'inline-block';
                button.style.display = 'none';
            } else {
                console.log("保存失败");
                alert('商品保存失败');
            }
            response.json()
        }) // 解析响应为 JSON 格式

        .catch(error => {
            // 处理错误
            console.error('Error:', error);
        });

}


    function imagetoFile(image,imageName,formData,button){
        var file
        var cvs = document.createElement("canvas");
        var ctx = cvs.getContext('2d');
        cvs.width = image.width;
        cvs.height = image.height;
        ctx.drawImage(image, 0, 0, cvs.width, cvs.height);
        console.log('cvs='+cvs);
        cvs.toBlob(function(blob) {
            // 在此处处理生成的 Blob 对象
            console.log('blob='+blob);
             file = new File([blob], imageName, { type: blob.type });
            formData.append('pic', file);
            console.log('file2='+file);
            if (typeof file === 'object' && file instanceof File) {
                console.log('文件已生成');
            } else {
                console.log('文件未生成');
            }

            for (var pair of formData.entries()) {
                console.log(pair[0] + ', ' + pair[1]);
            }
           sendSaveReq(button,formData);


        }, 'image/png');

    };




        function previewImage1(event) {
            var input = event.target;
            var row = input.parentNode.parentNode;

            console.log('选择图片');

            // var preview = row.getElementById('imagePreview1');
            var preview = row.querySelector('img')
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    preview.src = e.target.result;
                    console.log(preview.src);
                    preview.style.display = 'block'; // 在if语句块中显示预览图片
                }
                reader.readAsDataURL(input.files[0]);
            } else if (saveButton.style.display === 'none') {
                console.log('不可编辑');
            }
        }


        //返回为空
        function searchCategory() {
            var keyword = document.getElementById('keyword').value;
            console.log(keyword);
            var url = '/admin/getCategoryListByKeyForJS?keyword=' + keyword;
            fetch(url)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok.');
                    }
                    return response.json(); // 解析JSON格式的响应数据
                })
                .then(data => {
                    // 处理返回的数据
                    console.log(data);
                    tbody.innerHTML = '';
                    var newProducts = data.data;
                    updateTbody(newProducts);
                })
                .catch(error => {
                    console.error('请求发生错误', error);
                });
        }

        function deleteCategory(button) {
            var row = button.parentNode.parentNode;
            var catid = row.querySelector('td:nth-child(1)').innerText;

            var result = confirm("Are you sure you want to delete the category " + catid + "?");
            const url = `/admin/deleteCategoryById?categoryId=${catid}`;
            if (result) {
                fetch(url, {
                    method: 'GET' // 使用 GET 方法
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.message != null) {
                            alert('删除失败:' + data.message);
                        } else {
                            alert('删除成功');
                            row.remove();
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                    });
            }

    }

</script>
</body>
</html>